package org.smallreunion.model;

import java.io.Serializable;
import java.util.Date;

import org.slim3.datastore.Attribute;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.Model;
import org.smallreunion.util.DateUtil;
import org.smallreunion.var.LoginInfo;

import com.google.appengine.api.datastore.Key;

/**
 * AuthToken
 *
 * @author Sinmetal
 *
 */
@Model(schemaVersion = 1)
public class AuthToken implements Serializable {

    private static final long serialVersionUID = 1L;

    @Attribute(primaryKey = true)
    private Key key;

    private Key memberKey;

    private Date expires;

    /**
     * Returns the key.
     *
     * @return the key
     */
    public Key getKey() {
        return key;
    }

    /**
     * Sets the key.
     *
     * @param key
     *            the key
     */
    public void setKey(Key key) {
        this.key = key;
    }

    /**
     * @return memberKey
     */
    public Key getMemberKey() {
        return memberKey;
    }

    /**
     * @param memberKey
     *            セットする memberKey
     */
    public void setMemberKey(Key memberKey) {
        this.memberKey = memberKey;
    }

    /**
     * @return expires
     */
    public Date getExpires() {
        return expires;
    }

    /**
     * @param expires
     *            セットする expires
     */
    public void setExpires(Date expires) {
        this.expires = expires;
    }

    /**
     * Key作成
     *
     * @param token
     * @return
     */
    public static Key createKey(String token) {
        return Datastore.createKey(AuthToken.class, token);
    }

    /**
     * インスタンス生成
     *
     * @param token
     * @param info
     * @param timeout
     * @return
     */
    public static AuthToken getInstance(String token, LoginInfo info,
            int timeout) {
        AuthToken authToken = new AuthToken();
        authToken.setKey(AuthToken.createKey(token));
        authToken.setMemberKey(info.getKey());
        long expires = DateUtil.getNow().getTime() + timeout;
        authToken.setExpires(new Date(expires));
        return authToken;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        AuthToken other = (AuthToken) obj;
        if (key == null) {
            if (other.key != null) {
                return false;
            }
        } else if (!key.equals(other.key)) {
            return false;
        }
        return true;
    }
}
